"""
Command-line interface helper functions
"""
import os
import sys
import argparse
import textwrap

def create_parser():
    """
    Create command-line argument parser
    
    Returns:
    --------
    argparse.ArgumentParser
        Argument parser
    """
    # Create parser
    parser = argparse.ArgumentParser(
        description='Smart Mesh Optimizer - A tool for intelligent mesh optimization',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=textwrap.dedent('''
            Examples:
            ---------
            # Analyze mesh quality
            python -m smart_mesh_optimizer analyze --input mesh.stl
            
            # Optimize mesh using Laplacian smoothing
            python -m smart_mesh_optimizer optimize --input mesh.stl --output optimized.stl --method laplacian
            
            # Optimize mesh using smart smoothing with 20 iterations
            python -m smart_mesh_optimizer optimize --input mesh.stl --output optimized.stl --method smart --iterations 20
            
            # Optimize mesh using AI-based approach
            python -m smart_mesh_optimizer optimize --input mesh.stl --output optimized.stl --method ai
            
            # Visualize mesh quality
            python -m smart_mesh_optimizer visualize --input mesh.stl
            
            # Compare original and optimized meshes
            python -m smart_mesh_optimizer compare --original mesh.stl --optimized optimized.stl
        ''')
    )
    
    # Create subparsers for different commands
    subparsers = parser.add_subparsers(dest='command', help='Command to execute')
    
    # Analyze command
    analyze_parser = subparsers.add_parser('analyze', help='Analyze mesh quality')
    analyze_parser.add_argument('--input', '-i', required=True, help='Input mesh file')
    analyze_parser.add_argument('--visualize', '-v', action='store_true', help='Visualize mesh quality')
    analyze_parser.add_argument('--save-plot', '-p', help='Save quality histogram to file')
    
    # Optimize command
    optimize_parser = subparsers.add_parser('optimize', help='Optimize mesh quality')
    optimize_parser.add_argument('--input', '-i', required=True, help='Input mesh file')
    optimize_parser.add_argument('--output', '-o', required=True, help='Output mesh file')
    optimize_parser.add_argument('--method', '-m', choices=['laplacian', 'smart', 'ai'], 
                                default='smart', help='Optimization method')
    optimize_parser.add_argument('--iterations', '-n', type=int, default=10, 
                                help='Number of optimization iterations')
    optimize_parser.add_argument('--threshold', '-t', type=float, default=2.0, 
                                help='Quality threshold for identifying poor elements')
    optimize_parser.add_argument('--visualize', '-v', action='store_true', 
                                help='Visualize mesh before and after optimization')
    optimize_parser.add_argument('--save-plot', '-p', help='Save quality comparison plot to file')
    
    # Visualize command
    visualize_parser = subparsers.add_parser('visualize', help='Visualize mesh')
    visualize_parser.add_argument('--input', '-i', required=True, help='Input mesh file')
    visualize_parser.add_argument('--quality', '-q', action='store_true', 
                                help='Visualize mesh quality')
    visualize_parser.add_argument('--save-plot', '-p', help='Save visualization to file')
    
    # Compare command
    compare_parser = subparsers.add_parser('compare', help='Compare two meshes')
    compare_parser.add_argument('--original', '-o', required=True, help='Original mesh file')
    compare_parser.add_argument('--optimized', '-m', required=True, help='Optimized mesh file')
    compare_parser.add_argument('--visualize', '-v', action='store_true', 
                                help='Visualize mesh comparison')
    compare_parser.add_argument('--save-plot', '-p', help='Save comparison plot to file')
    
    return parser

def validate_args(args):
    """
    Validate command-line arguments
    
    Parameters:
    -----------
    args : argparse.Namespace
        Parsed arguments
        
    Returns:
    --------
    bool
        True if arguments are valid, False otherwise
    """
    # Check if command is specified
    if args.command is None:
        print("Error: No command specified")
        return False
    
    # Check if input files exist
    if hasattr(args, 'input') and args.input:
        if not os.path.exists(args.input):
            print(f"Error: Input file not found: {args.input}")
            return False
    
    if hasattr(args, 'original') and args.original:
        if not os.path.exists(args.original):
            print(f"Error: Original file not found: {args.original}")
            return False
    
    if hasattr(args, 'optimized') and args.optimized:
        if not os.path.exists(args.optimized):
            print(f"Error: Optimized file not found: {args.optimized}")
            return False
    
    # Check if output directory exists
    if hasattr(args, 'output') and args.output:
        output_dir = os.path.dirname(args.output)
        if output_dir and not os.path.exists(output_dir):
            try:
                os.makedirs(output_dir, exist_ok=True)
            except Exception as e:
                print(f"Error: Cannot create output directory: {output_dir}")
                print(f"       {e}")
                return False
    
    return True

def print_header():
    """Print application header"""
    header = """
    ╔═══════════════════════════════════════════════════════════╗
    ║                                                           ║
    ║               SMART MESH OPTIMIZER                        ║
    ║                                                           ║
    ║       Intelligent mesh quality analysis and optimization  ║
    ║                                                           ║
    ╚═══════════════════════════════════════════════════════════╝
    """
    print(header)

def print_mesh_stats(mesh_data):
    """
    Print mesh statistics
    
    Parameters:
    -----------
    mesh_data : dict
        Dictionary containing mesh data
    """
    if 'points' in mesh_data and 'cells' in mesh_data:
        num_points = len(mesh_data['points'])
        num_cells = len(mesh_data['cells'])
        
        print("\nMesh Statistics:")
        print(f"  - Number of points: {num_points}")
        print(f"  - Number of cells: {num_cells}")

def print_quality_metrics(quality_metrics):
    """
    Print quality metrics
    
    Parameters:
    -----------
    quality_metrics : dict
        Dictionary containing quality metrics
    """
    print("\nQuality Metrics:")
    print(f"  - Minimum quality: {quality_metrics['min_quality']:.4f}")
    print(f"  - Maximum quality: {quality_metrics['max_quality']:.4f}")
    print(f"  - Average quality: {quality_metrics['avg_quality']:.4f}")
    print(f"  - Standard deviation: {quality_metrics['std_quality']:.4f}")

def print_optimization_results(optimization_results):
    """
    Print optimization results
    
    Parameters:
    -----------
    optimization_results : dict
        Dictionary containing optimization results
    """
    improvement = optimization_results['improvement']
    
    print("\nOptimization Results:")
    print(f"  - Original average quality: {improvement['original_avg_quality']:.4f}")
    print(f"  - Optimized average quality: {improvement['optimized_avg_quality']:.4f}")
    print(f"  - Improvement percentage: {improvement['improvement_percentage']:.2f}%") 